package com.pc.store.service.impl;

import com.pc.store.entity.User;
import com.pc.store.mapper.UserMapper;
import com.pc.store.service.IUserService;
import com.pc.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;

/**
 * 用户模块业务层实现类
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void reg(User user){
        String username = user.getUsername();

        User result = userMapper.findByUsername(username);

        if(result != null){
            throw new UsernameDuplicatedException("用户名已被占用");
        }
        /*
        进行数据的加密
         */
        String oldpassword = user.getPassword();

        //随机生成一个大写随机字符串的salt值
        String salt = UUID.randomUUID().toString().toUpperCase();

        String md5password = getMD5Password(oldpassword, salt);
        user.setSalt(salt);

        user.setPassword(md5password);

        //补全数据
        user.setIsDelete(0);
        user.setCreatedUser(user.getUsername());
        user.setModifiedUser(user.getUsername());
        Date date = new Date();
        user.setCreatedTime(date);
        user.setModifiedTime(date);

        Integer rows = userMapper.insert(user);
        if(rows != 1){
            throw  new InsertException("用户注册时产生了未知异常");
        }
    }

    @Override
    public User login(String username, String password) {
        //查询用户名称的数据是否存在,不存在则抛出异常
        User result=userMapper.findByUsername(username);

        if(result == null){
            throw new UserNotFoundException("用户数据不存在");
        }

        //检测用户的密码是否匹配.先获取数据库中加密后的密码,再和用户传递过来的密码进行比较,相同MD5规则加密
        String oldpassword = result.getPassword();
        String salt=result.getSalt();
        String newMd5Password = getMD5Password(password,salt);
        if(!newMd5Password.equals(oldpassword)){
            throw new PasswordNotMatchException("用户密码错误");
        }
        //判断is_delete字段的值是否为1,为1表示被标记为删除
        if(result.getIsDelete() == 1){
            throw new UserNotFoundException("用户数据不存在");
        }

        //调用mapper层的findbyusername方法来查询用户的数据
        User user=new User();
        user.setUid(result.getUid());
        user.setUsername(result.getUsername());
        user.setAvatar(result.getAvatar() );

        //将当前的用户数据返回
        return user;
    }

    @Override
    public void changePassword(Integer uid, String username, String oldPassword, String newPassword) {
        User result = userMapper.findByUid(uid);
        if(result==null||result.getIsDelete()==1){
            throw new UpdateException("用户数据异常");
        }

        String oldMd5Password = getMD5Password(oldPassword,result.getSalt());

        if(!result.getPassword().equals(oldMd5Password)){
            throw new UpdateException("密码错误");
        }

        String newMd5Password = getMD5Password(newPassword,result.getSalt());
        Integer rows = userMapper.updatePasswordByUid(uid, newMd5Password, username, LocalDateTime.now());
        if(rows!=1){
            throw new UpdateException("更新数据产生未知异常");
        }
    }

    @Override
    public User getByUid(Integer uid) {
        User result = userMapper.findByUid(uid);
        if(result == null || result.getIsDelete()==1){
            throw new UserNotFoundException("用户数据不存在");
        }
        User user = new User();
        user.setUsername(result.getUsername());
        user.setPhone(result.getPhone());
        user.setEmail(result.getEmail());
        user.setGender(result.getGender());

        return user;
    }

    @Override
    public void changeInfo(Integer uid, String username, User user) {
        User result = userMapper.findByUid(uid);
        if(result == null || result.getIsDelete()==1){
            throw new UserNotFoundException("用户数据不存在");
        }
        user.setUid(uid);
        user.setModifiedUser(username);
        user.setModifiedTime(new Date());

       Integer rows = userMapper.updateInfoByUid(user);
       if(rows!=1){
           throw new UpdateException("更新数据时产生未知的异常");
       }
    }

    @Override
    public void changeAvatar(Integer uid, String avatar, String username) {
        User result = userMapper.findByUid(uid);
        if(result == null|| result.getIsDelete().equals(1)){
            throw  new UserNotFoundException("用户数据不存在");
        }
        Integer rows = userMapper.updateAvatarByUid(uid, avatar, username,LocalDateTime.now());
        if(rows!= 1){
            throw new UpdateException("更新数据时产生未知的异常");
        }
    }

    /**
     * 额外定义一个MD5算法加密
     */
    private String getMD5Password(String password, String salt){
        for(int i = 0; i < 3;i++){
            password = DigestUtils.md5DigestAsHex((salt+password+salt).getBytes()).toUpperCase();
        }
        return password;
    }
}
